﻿namespace LaoLuo
{
    using System;
    using System.Collections.Concurrent;

    /// <summary>
    /// 单例的容器
    /// </summary>
    public static class SingleInstanceContainer
    {
        /// <summary>
        /// 容器
        /// </summary>
        private static readonly ConcurrentDictionary<Type, object> Container = new ConcurrentDictionary<Type, object>();

        /// <summary>
        /// 获取指定类型的单例
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <returns>单例</returns>
        public static T GetInstance<T>()
            where T : class, new()
        {
            return Container.GetOrAdd(typeof(T), (type) => { return new T(); }) as T;
        }

        /// <summary>
        /// 获取指定类型的用户添加或设置的单例
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static T GetUserSetInstance<T>()
            where T : class
        {
            object value;
            Container.TryGetValue(typeof(T), out value);
            return value as T;
        }

        /// <summary>
        /// 设置指定类型的单例
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="value">单例</param>
        public static void SetInstance<T>(T value)
        {
            Container[typeof(T)] = value;
        }

        /// <summary>
        /// 添加指定类型的单例
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="value">单例</param>
        /// <returns>是否添加成功</returns>
        public static bool AddInstance<T>(T value)
        {
            return Container.TryAdd(typeof(T), value);
        }
    }
}
